import pandas as pd

df = pd.read_csv('static/data/rank_info_pre.csv')


def ratio_type():
    df_type_ratio = df[['类别', '作品']].groupby('类别').count().reset_index()
    data = [{'name': i[0], 'value': i[1]} for i in df_type_ratio.values]
    return {
        'data': data
    }


def author_mention_times_top10():
    df_all_rank_author_mention_times_top10 = (df[['作者', '作品']]
                                              .groupby('作者')
                                              .count()
                                              .sort_values('作品', ascending=False)
                                              .head(10)
                                              .reset_index())
    name = df_all_rank_author_mention_times_top10['作者'].values.tolist()
    value = df_all_rank_author_mention_times_top10['作品'].values.tolist()
    return {
        'name': name,
        'value': value
    }


def tree_data():
    df_rank_group = df[['排名', '作品', '类别', '排行榜']].groupby('排行榜')
    data = [
        {
            'name': i[0],
            'children': [
                {
                    'name': j[0],
                    'children': [
                        {
                            'name': '{}-{}'.format(k[0], k[1])
                        } for k in j[1][['排名', '作品']].values.tolist()
                    ]
                } for j in i[1].groupby('类别')
            ]
        } for i in df_rank_group
    ]
    return {
        'name': '全部榜单',
        'children': data
    }


def funnel_data():
    df_funnel = df[['作品', '类别', '状态', '排名']]
    df_category = df_funnel[df_funnel['类别'] == '东方玄幻']
    df_status = df_category[df_category['状态'] == '完本']
    df_rank = df_status[df_status['排名'] <= 10]
    return {
        'name': ['东方玄幻', '完本', '排名前十'],
        'value': [
            {
                'value': 100,
                'name': '全部'
            },
            {
                'value': round(len(df_category) / len(df) * 100, 2),
                'name': '东方玄幻'
            },
            {
                'value': round(len(df_status) / len(df) * 100, 2),
                'name': '完本'
            },
            {
                'value': round(len(df_rank) / len(df) * 100, 2),
                'name': '排名前十'
            }
        ]
    }


def line_data():
    week_day = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
    df['更新时间'] = df['更新时间'].apply(lambda x: pd.to_datetime(x))
    df['星期'] = df['更新时间'].apply(lambda x: x if pd.isnull(x) else week_day[int(x.weekday())])
    df_update_weekday = df.drop_duplicates(subset=['作品'], keep='first', inplace=False).dropna(axis=0, how='all',
                                                                                                subset=['星期'])
    data_list = df_update_weekday.groupby('星期').count()['作品'].reset_index().values.tolist()
    data_dict = {i[0]: i[1] for i in data_list}
    value = [data_dict[i] for i in week_day]
    return {
        'name': week_day,
        'value': value
    }
